package cn.ubest.mvvmcore.http

import cn.ubest.mvvmcore.BuildConfig
import cn.ubest.mvvmcore.http.converter.CustomJsonConverterFactory
import com.facebook.stetho.okhttp3.StethoInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

class RetrofitFactory private constructor() {
    companion object {
        val interceptList = mutableListOf<Interceptor>()
        var baseUrl = ""

        const val READ_TIMEOUT = 60L // 读取超时时间,单位秒
        const val CONN_TIMEOUT = 60L // 连接超时时间,单位秒

        val retrofit: Retrofit by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            //initOkHttpClient
            val loggingInterceptor = HttpLoggingInterceptor()
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            val builder = OkHttpClient.Builder()
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)

            for (intercept in interceptList) {
                builder.addInterceptor(intercept)
            }
            //debug时开启网络请求打印
            if (BuildConfig.DEBUG) {
                builder.addInterceptor(loggingInterceptor)
                    .addNetworkInterceptor(StethoInterceptor())
            }

            //initRetrofit
            Retrofit.Builder()
                .baseUrl(baseUrl)
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(CustomJsonConverterFactory.create())
                .client(builder.build())
                .callbackExecutor(Executors.newFixedThreadPool(1))
                .build()
        }
    }
}